import { useState, useCallback } from 'react'
import { View } from 'react-native'
import { createStyles, useStyles } from '@mf2e/react-native-theme-styles'
import Modal from 'react-native-modal'

const BasePopup = ({ style, children, fromRef, visible, onClose, ...otherProps }) => {
  const styles = useStyles(themeStyles)

  const [positionStyle, setPositionStyle] = useState()

  const onLayout = useCallback(() => {
    fromRef.current?.measureInWindow((x, y) => {
      setPositionStyle({ top: y, left: x })
    })
  }, [fromRef])

  return (
    <Modal
      style={styles.BasePopup}
      isVisible={visible}
      backdropOpacity={0}
      animationIn="fadeIn"
      animationOut="fadeOut"
      useNativeDriver={true}
      useNativeDriverForBackdrop={true}
      hideModalContentWhileAnimating={true}
      onBackdropPress={onClose}
      onBackButtonPress={onClose}
      onLayout={onLayout}
      {...otherProps}
    >
      <View style={[styles.popup, positionStyle, style]}>{children}</View>
    </Modal>
  )
}

const themeStyles = createStyles({
  BasePopup: {
    flex: 1,
    margin: 0,
  },
  popup: {
    position: 'absolute',
  },
})

export default BasePopup
